package com.bigfans.framework.neo4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Values;

public class Neo4jTemplate {

	private Neo4jConnectionFactory connectionFactory;

	public Neo4jTemplate(Neo4jConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public StatementResult createNode(String sql, Map<String, Object> params) {
		Session session = connectionFactory.getDriver().session();
		session.run("CREATE (a:Person {name: {name}, title: {title}})",
				Values.parameters("name", "Arthur", "title", "King"));

		StatementResult result = session.run(
				"MATCH (a:Person) WHERE a.name = {name} " + "RETURN a.name AS name, a.title AS title",
				Values.parameters("name", "Arthur"));
		while (result.hasNext()) {
			Record record = result.next();
			System.out.println(record.get("title").asString() + " " + record.get("name").asString());
		}
		session.close();
		return result;
	}
	
	public StatementResult test() {
		Session session = connectionFactory.getDriver().session();
		StatementResult result = session.run(
				"MATCH (a:Person) WHERE a.name = {name} " + "RETURN a.name AS name, a.title AS title",
				Values.parameters("name", "Arthur"));
		while (result.hasNext()) {
			Record record = result.next();
			System.out.println(record.get("title").asString() + " " + record.get("name").asString());
		}
		session.close();
		return result;
	}

	public <T> List<T> queryList(String sql, Neo4jRowMapper<T> mapper, Object... params) {
		Session session = null;
		List<T> dataList = null;
		try {
			session = connectionFactory.getDriver().session();
			StatementResult result = session.run(sql);
			dataList = new ArrayList<T>();
			while (result.hasNext()) {
				Record record = result.next();
				T obj = mapper.map(record);
				dataList.add(obj);
			}
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return dataList;
	}

	public <T> List<T> queryList(String sql, Map<String, Object> params) {
		return null;
	}
}
